package gold.digger;

import gold.utils.InputUtil;
import gold.vo.TreeNode;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC958 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public boolean isCompleteTree(TreeNode root) {
            if (null == root) return true;
            Queue<TreeNode> curLayer = new LinkedList<>();
            int curDepth = 0;
            curLayer.add(root);
            while (!curLayer.isEmpty()) {
                int size = curLayer.size();
                if (size == Math.pow(2, curDepth++)) {
                    // 当前层是满的
                    boolean nextLayerAlreadyStop = false;
                    for (int i = 0; i < size; i++) {
                        TreeNode cur = curLayer.poll();
                        if (nextLayerAlreadyStop && (null != cur.left || null != cur.right)) return false;
                        if (null == cur.left && null != cur.right) return false;
                        if (null == cur.left || null == cur.right) nextLayerAlreadyStop = true;
                        if (null != cur.left) curLayer.offer(cur.left);
                        if (null != cur.right) curLayer.offer(cur.right);
                    }

                } else {
                    // 当前层非满，必须是最后一层
                    for (int i = 0; i < size; i++) {
                        TreeNode cur = curLayer.poll();
                        if (null != cur.left || null != cur.right) return false;
                    }
                }
            }

            return true;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.isCompleteTree(TreeNode.createTree("[1,2,3,4,5,6]")));
        System.out.println(solution.isCompleteTree(TreeNode.createTree("[1,2,3,4,5,null,7]")));
        System.out.println(solution.isCompleteTree(TreeNode.createTree("[1,2,3,5,null,7,8]")));
    }

    public static void main(String[] args) throws Exception {
        LC958 an = new LC958();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
